#!/usr/bin/python
"""

   parse_intron_exon.py

        given a raw genomic dna file,
        splits into introns and exons use upper/lower case
"""

from optparse import OptionParser
import sys, os
import re
import StringIO


import sys

# add self to search path for testing
if __name__ == '__main__':
    sys.path.append("../python_modules")

from general_util import die_error

# add self to search path for testing
if __name__ == '__main__':
    exe_path = os.path.split(os.path.abspath(sys.argv[0]))[0]
    sys.path.append(os.path.abspath(os.path.join(exe_path,"..", "python_modules")))

import general_util
from custom_log import custom_log
from general_util import die_error




parser = OptionParser(version="%prog 1.0")
parser.add_option("-d", "--dna", dest="dnafile",
                  metavar="FILE",                       
                  type="string",
                  help="name and path of dna file")
parser.set_defaults(dnafile = "") 

# get help string
f =StringIO.StringIO()
parser.print_help(f)
helpstr = f.getvalue()
(options, args) = parser.parse_args()

def line_wrap (s, count):
    length = len(s)
    lines = []
    for x in range(0,  length, count):
        lines.append(s[x:x+count])
    return "\n".join(lines)

if not len(options.dnafile):
    die_error("Please specify a file in --dna.\n\n"+helpstr)
dna = open(options.dnafile).read()
dna = dna.replace(" ", "")
dna = dna.replace("\n", "")

import re
splitpatt = re.compile("([a-z]+)")
match_results = splitpatt.split(dna)
lowercase = re.compile("([a-z]+)")
count_intron = 1
count_exon = 1
for x in match_results:
    if not x:
        continue
    if lowercase.match(x[0]):
        print ">intron " + str(count_intron) + "\n" + line_wrap(x, 60)
        count_intron += 1
    else:
        print ">exon " + str(count_exon) + "\n" + line_wrap(x, 60)
        count_exon += 1


